package com.wunu.smartlock1.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.AbsListView;
import android.widget.ListView;
import android.view.View.OnClickListener;

import com.google.gson.reflect.TypeToken;
import com.wunu.smartlock1.R;
import com.wunu.smartlock1.adapter.AuthorizedRecordAdapter;
import com.wunu.smartlock1.model.AuthorizedRecordVo;
import com.wunu.smartlock1.net.NetComponent;
import com.wunu.smartlock1.net.api.LockEventApi;
import com.wunu.smartlock1.net.response.ApiNormalResponse;
import com.wunu.smartlock1.net.response.LockEvent;
import com.wunu.smartlock1.net.response.LockQrCode;
import com.wunu.smartlock1.util.CommonUtil;

import android.widget.CheckBox;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;

import android.view.View;
import android.widget.Toast;

import retrofit2.Call;

/**
 * 开锁记录
 * Created by admin on 2018/4/21.
 */

public class LockRecordActivity extends AppCompatActivity {
    private int lockId;
    private int group = 0;
    private int pageIndex = 1;
    private int pageSize = 10;

    List<AuthorizedRecordVo> rootList = new ArrayList<AuthorizedRecordVo>();
    List<AuthorizedRecordVo> comList = new ArrayList<AuthorizedRecordVo>();
    ListView listView;
    private View footer;
    private boolean loadFinishFlag;
    LockEventApi service = NetComponent.getRetrofit().create(LockEventApi.class);

    public static boolean isChecked = true;
    private CheckBox authorized;
    private CheckBox tempoary;
    AuthorizedRecordAdapter adapter;
    String toast = "aaa";

    private ProgressDialog pd;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            System.out.println("msg----------------------->:"+msg);
            System.out.println("obj->"+msg.getData());
            loadFinishFlag = true;
            if (msg.obj != null){
                if (isChecked){
                    rootList.addAll(CommonUtil.transLockEventList((List<LockEvent>)msg.obj));
                }else{
                    comList.addAll(CommonUtil.transLockEventList((List<LockEvent>)msg.obj));
                }
            }
            pd.dismiss();
            adapter.notifyDataSetChanged();
            System.out.println("obj:"+msg.obj);
        }
    };
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.smartlock_activity_lockrecord);
        tempoary = (CheckBox) findViewById(R.id.tempoary);
        authorized = (CheckBox) findViewById(R.id.authorized);

        footer = getLayoutInflater().inflate(R.layout.smartlock_footer, null);
        adapter = new AuthorizedRecordAdapter(LockRecordActivity.this, R.layout.smartlock_activity_lockrecord_item, rootList);
        listView = (ListView) findViewById(R.id.recordListView);
        listView.setAdapter(adapter);
        listView.addFooterView(footer);
        listView.setOnScrollListener(new ScrollListener());
        listView.removeFooterView(footer);
        loadFinishFlag = true;

        //取得从上一个Activity当中传递过来的Intent对象
        Intent intent = getIntent();
        lockId = Integer.parseInt(intent.getStringExtra("lockId"));
        System.out.println("从主界面传递过来的开锁记录lockId: "+lockId);
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println("2从主界面传递过来的lockId: "+lockId);
                    Call<ApiNormalResponse<List<LockEvent>>> call = service.getLockEvents(lockId,group,pageIndex,pageSize);
                    ApiNormalResponse<List<LockEvent>> resp = call.execute().body();
                    // 发送消息，把服务器返回的本文弹出吐司显示
                    Message msg = handler.obtainMessage();
                    if(resp == null || resp.getData() == null)msg.obj = null;
                    else msg.obj = resp.getData().getData();
                    toast = "开锁记录";
                    System.out.println(toast+":"+msg.obj);
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    System.out.println("开锁记录异常:" + e);
                }
            }
        };
        //构建一个下载进度条
        pd= ProgressDialog.show(LockRecordActivity.this, "请等待", "获取数据中…");
        thread.start();

        authorized.setChecked(isChecked);
        tempoary.setChecked(!isChecked);



        authorized.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                isChecked = true;
                tempoary.setChecked(false);
                authorized.setChecked(true);
                adapter =new AuthorizedRecordAdapter(LockRecordActivity.this, R.layout.smartlock_activity_lockrecord_item, rootList);
                listView.setAdapter(adapter);
            }
        });

        tempoary.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                isChecked = false;
                tempoary.setChecked(true);
                authorized.setChecked(false);
                adapter =new AuthorizedRecordAdapter(LockRecordActivity.this, R.layout.smartlock_activity_lockrecord_item, comList);
                listView.setAdapter(adapter);
            }
        });
}


    public List<AuthorizedRecordVo> getMemberList(List<AuthorizedRecordVo> alllist,boolean flag){
        List<AuthorizedRecordVo> list = new ArrayList<AuthorizedRecordVo>();
        for(int i=0;i<alllist.size();i++){
            if (((flag & alllist.get(i).isRoot() ) || !(flag | alllist.get(i).isRoot()))){
                list.add(alllist.get(i));
            }
        }
        return list;
    }



    public final class ScrollListener implements AbsListView.OnScrollListener {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case SCROLL_STATE_IDLE:
                    break;
                case SCROLL_STATE_TOUCH_SCROLL:
                    break;
                case SCROLL_STATE_FLING:
                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            //获取屏幕最后Item的ID
            int lastVisibleItem = listView.getLastVisiblePosition();
            System.out.println("专门测试临时秘钥发的空请求lastVisibleItem:"+lastVisibleItem);
            if(lastVisibleItem == -1 || lastVisibleItem == 0) return;//BUG:当没有查到数据时，一直在调用本onScroll方法,然后增加刷新页数，目前这样暂时处理
            if (lastVisibleItem + 1 == totalItemCount) {
                System.out.println("专门测试临时秘钥发的空请求totalItemCount:"+totalItemCount);
                if (loadFinishFlag) {
                    //标志位，防止多次加载
                    loadFinishFlag = false;
                    //listView.addFooterView(footer);
                    //开线程加载数据
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                Thread.sleep(300);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            pageIndex++;
                            group = isChecked?0:1;
                            System.out.println("专门测试临时秘钥发的空请求pageIndex:"+pageIndex+"\tgroup:"+group);
                            try {
                                Call<ApiNormalResponse<List<LockEvent>>> call = service.getLockEvents(lockId,group,pageIndex,pageSize);
                                ApiNormalResponse<List<LockEvent>> resp = call.execute().body();
                                // 发送消息，把服务器返回的本文弹出吐司显示
                                Message msg = handler.obtainMessage();
                                if(resp == null || resp.getData() == null)msg.obj = null;
                                else msg.obj = resp.getData().getData();
                                toast = "开锁记录---";
                                System.out.println(toast+":"+msg.obj);
                                handler.sendMessage(msg);
                            } catch (Exception e) {
                                System.out.println("开锁记录异常:" + e);
                            }
                        }
                    }.start();
                }
            }
        }
    }
}
